<template>
  <div class="departments-container">
    <div class="page-header">
      <h2 class="page-title">部门管理</h2>
      <el-button type="primary" @click="handleAdd">新增部门</el-button>
    </div>
    
    <div class="search-bar">
      <el-input
        v-model="searchText"
        placeholder="搜索部门名称"
        class="search-input"
        clearable
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>
    
    <el-table
      :data="filteredDepartments"
      style="width: 100%"
      border
      stripe
      v-loading="loading"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="部门名称" />
      <el-table-column prop="description" label="描述" />
      <el-table-column prop="userCount" label="用户数量" width="100" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            plain
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            size="small"
            plain
            @click="handleDelete(scope.row)"
            :disabled="scope.row.userCount > 0"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 新增/编辑部门对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑部门' : '新增部门'"
      width="500px"
    >
      <el-form
        ref="departmentFormRef"
        :model="departmentForm"
        :rules="departmentRules"
        label-width="100px"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="departmentForm.name" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="departmentForm.description" type="textarea" rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/utils/api'

// 部门列表
const departments = ref([])
const loading = ref(false)

// 搜索条件
const searchText = ref('')

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const submitLoading = ref(false)
const departmentFormRef = ref(null)

// 部门表单
const departmentForm = reactive({
  id: null,
  name: '',
  description: ''
})

// 表单验证规则
const departmentRules = {
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ]
}

// 过滤后的部门列表
const filteredDepartments = computed(() => {
  if (!searchText.value) {
    return departments.value
  }
  
  const keyword = searchText.value.toLowerCase()
  return departments.value.filter(dept => {
    return dept.name.toLowerCase().includes(keyword) || 
           (dept.description && dept.description.toLowerCase().includes(keyword))
  })
})

// 获取部门列表
const fetchDepartments = async () => {
  loading.value = true
  try {
    const response = await api.get('/departments')
    if (response.data && response.data.status === 'success') {
      departments.value = response.data.data
    } else {
      ElMessage.error('获取部门列表失败: ' + (response.data?.message || '未知错误'))
    }
  } catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error('获取部门列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  // 直接使用计算属性过滤，无需额外操作
}

// 重置搜索条件
const resetSearch = () => {
  searchText.value = ''
}

// 新增部门
const handleAdd = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 编辑部门
const handleEdit = (row) => {
  isEdit.value = true
  departmentForm.id = row.id
  departmentForm.name = row.name || ''
  departmentForm.description = row.description || ''
  dialogVisible.value = true
}

// 删除部门
const handleDelete = (row) => {
  // 检查部门是否有关联用户
  if (row.userCount > 0) {
    ElMessage.warning('无法删除有关联用户的部门，请先移除关联的用户')
    return
  }
  
  ElMessageBox.confirm(`确定要删除部门"${row.name}"吗？此操作不可恢复！`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      loading.value = true
      
      const response = await api.delete(`/departments/${row.id}`)
      
      if (response.data && response.data.status === 'success') {
        ElMessage.success('删除成功')
        // 重新获取部门列表
        fetchDepartments()
      } else {
        ElMessage.error('删除失败: ' + (response.data?.message || '未知错误'))
      }
    } catch (error) {
      console.error('删除部门失败:', error)
      ElMessage.error('删除部门失败')
    } finally {
      loading.value = false
    }
  }).catch(() => {
    // 用户取消删除，不做任何处理
  })
}

// 重置表单
const resetForm = () => {
  if (departmentFormRef.value) {
    departmentFormRef.value.resetFields()
  }
  
  Object.assign(departmentForm, {
    id: null,
    name: '',
    description: ''
  })
}

// 提交表单
const submitForm = async () => {
  if (!departmentFormRef.value) return
  
  departmentFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      
      try {
        // 准备提交的数据
        const departmentData = { ...departmentForm }
        
        let response
        
        if (isEdit.value) {
          // 编辑部门
          response = await api.put(`/departments/${departmentData.id}`, departmentData)
        } else {
          // 新增部门
          response = await api.post('/departments', departmentData)
        }
        
        if (response.data && response.data.status === 'success') {
          ElMessage.success(isEdit.value ? '部门编辑成功' : '部门添加成功')
          dialogVisible.value = false
          // 重新获取部门列表
          fetchDepartments()
        } else {
          ElMessage.error((isEdit.value ? '编辑' : '添加') + '部门失败: ' + (response.data?.message || '未知错误'))
        }
      } catch (error) {
        console.error(isEdit.value ? '编辑部门失败:' : '添加部门失败:', error)
        ElMessage.error(isEdit.value ? '编辑部门失败' : '添加部门失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 页面加载时获取数据
onMounted(() => {
  fetchDepartments()
})
</script>

<style scoped>
.departments-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 22px;
  margin: 0;
}

.search-bar {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
}

.search-input {
  width: 300px;
}
</style> 